//
//  TiltingExampleViewController.m
//  TiltingExample
//

#import "TiltingExampleViewController.h"

@implementation TiltingExampleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	
	// 1/40초마다 가속도 데이터를 전달하도록 가속도계를 설정한다.
	[[UIAccelerometer sharedAccelerometer] setDelegate:self];
	[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1/40.0)];
	
	// 빨간색 사각형을 본문에 올려 놓는다.
	redBox = [[UIView alloc] initWithFrame:CGRectMake(110, 180, 100, 100)];
	redBox.backgroundColor = [UIColor redColor];
	[self.view addSubview:redBox];
}

- (void)moveBoxWithX:(float)xAmount andY:(float)yAmount {
	CGPoint boxCenter = redBox.center;
	boxCenter.x += xAmount;
	boxCenter.y += yAmount;
	
	// 화면 밖으로 넘어가지 않게 제한한다.
	if (boxCenter.x < 50.0)
		boxCenter.x = 50.0;
	if (boxCenter.x > 270.0)
		boxCenter.x = 270.0;
	if (boxCenter.y < 50.0)
		boxCenter.y = 50.0;
	if (boxCenter.y > 410.0)
		boxCenter.y = 410.0;
		
	redBox.center = boxCenter;
}

- (void)accelerometer:(UIAccelerometer *)accelerometer
		didAccelerate:(UIAcceleration *)acceleration {
	float sensitivity = 25.0f;
	float xDistance = acceleration.x * sensitivity;
	float yDistance = acceleration.y * -sensitivity;
	[self moveBoxWithX:xDistance andY:yDistance];
}

- (void)dealloc {
	[redBox release];
	redBox = nil;
	
    [super dealloc];
}

@end
